package com.lxt.filemanager.common;

import com.lxt.filemanager.entity.DFSAddress;
import org.csource.common.MyException;
import org.csource.fastdfs.*;

import java.io.IOException;

public class FastDFSUtil {
   private static TrackerClient trackerClient;
   private static TrackerServer trackerServer;
   private static StorageServer storageServer;
   static {
       try {
           ClientGlobal.init("fastdfs.conf");
           trackerClient=new TrackerClient();
           trackerServer=trackerClient.getTrackerServer();
            storageServer = trackerClient.getStoreStorage(trackerServer);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
    /**
     * 初始化获得连接
     * @return
     * @throws IOException
     * @throws MyException
     */
   public static StorageClient init(){
       StorageClient storageClient = new StorageClient(trackerServer,storageServer);
       return storageClient;
   }

    /**
     * 文件上传
     */
    public static DFSAddress upload(byte[] file, String extName) throws IOException, MyException {
        StorageClient sc = init();
        String[] fileInfo = sc.upload_file(file, extName, null);
        DFSAddress dfsAddress = new DFSAddress();
        dfsAddress.setGroup(fileInfo[0]);
        dfsAddress.setAddress(fileInfo[1]);
        sc.close();
        return dfsAddress;
    }

    /**
     * 下载文件
     */
    public static DFSAddress download(DFSAddress fileInfo) throws IOException, MyException {
        StorageClient sc = init();
        byte[] data = sc.download_file(fileInfo.getGroup(), fileInfo.getAddress());
        DFSAddress dfsAddress = new DFSAddress();
        dfsAddress.setData(data);
        sc.close();
        return dfsAddress;
    }

    /**
     * 删除文件
     */
    public static boolean delete(DFSAddress fileInfo) throws IOException, MyException {
        StorageClient sc = init();
        int i = sc.delete_file(fileInfo.getGroup(), fileInfo.getAddress());
        sc.close();
        return i == 0 ? true : false;
    }
}
